const validateUtil = require('../../utils/validateUtil')
const {
  sendCode
} = require('../../apis/api')
import Notify from '@vant/weapp/notify/notify'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    email: {
      type: String
    },
    value: {
      type: String,
      value: "发送验证码"
    },
    time: {
      type: Number,
      value: 120
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    sendCodeText: "发送验证码",
    sendCodeWait: 120,

    sendCodeStatus: false
  },

  /**
   * 组件生命周期
   */
  lifetimes: {
    attached() {
      this.setData({
        sendCodeText: this.data.value,
        sendCodeWait: this.data.time
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 发送验证码回调事件
     */
    _sendCode() {
      // 校验邮箱...
      if (!validateUtil.validateEmail(this.data.email)) {
        wx.showToast({
          title: '请输入正确的邮箱',
          icon: 'none'
        })
        return
      }
      // 发送验证码...
      sendCode(
        this.data.email,
        res => {
          if (res.data.code === 200) {
            // 发起成功通知
            Notify({
              type: 'success',
              message: '验证码发送成功',
              selector: "#notice",
              context: this
            })
          } else {
            Notify({
              type: 'danger',
              message: '发送失败，请稍后重试',
              selector: "#notice",
              context: this
            })
          }
        }
      )

      // 维护验证码按钮显示时效性
      this.setData({
        sendCodeStatus: true
      })
      let codeInterval = setInterval(() => {
        this.setData({
          sendCodeWait: this.data.sendCodeWait - 1,
          sendCodeText: this.data.sendCodeWait + 's'
        })
        if (this.data.sendCodeWait < 0) {
          // 重置定时器
          clearInterval(codeInterval)
          this.setData({
            sendCodeText: this.data.value,
            sendCodeWait: this.data.time,
            sendCodeStatus: false
          })
        }
      }, 1000)
    }
  }
})
